package com.chenjj.java.juc.tools.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 一个简单的CoundownLatch实现，为了弄清楚CoundownLatch源码里那些复杂的操作比我这个简单实现的优点在哪里。
 *
 * 通过一个AtomicInteger类型的计数器+ synchronized完成。
 */
public class CountDownLatchSimlpe extends CountDownLatch {
    private AtomicInteger count;
    private Object lock = new Object();

    public CountDownLatchSimlpe(int count) {
        super(count);
        this.count = new AtomicInteger(count);
    }

    @Override
    public void await() throws InterruptedException {
        synchronized (lock){
            lock.wait();
        }
    }

    @Override
    public void countDown() {
        synchronized (lock) {
            int c = count.decrementAndGet();
            if(c==0){
                lock.notifyAll();
            }
        }
    }
}
